<template>
  <div ref="chartContainer" style="width: 600px; height: 400px"></div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import type { Ref } from 'vue';
import * as echarts from 'echarts';
import { getAllUsers } from '@/api/user-api/userApi';
import type { DataItem } from '@/type/type';
// interface UserData{
//   name:string,
//   createTime:string,
// }
// 用户数据和计算使用时长
const userData: Ref<DataItem[]> = ref([]);

function calculateUsageDuration(createdAt: string) {
  const createdDate = new Date(createdAt);
  const currentDate = new Date();
  const durationInMs = currentDate - createdDate;
  const durationInDays = Math.floor(durationInMs / (1000 * 60 * 60 * 24));
  return durationInDays;
}

const chartContainer = ref(null);

onMounted(async () => {
  const response = await getAllUsers();
  userData.value = response;
  // for (let index = 0; index < response.length; index++) {
  //   userData.value[index].userAccount = response[index].userAccount;
  //   userData.value[index].createTime = response[index].createTime;
  // }
  const userDurations = userData.value.map(user => ({
    name: user.userAccount,
    duration: calculateUsageDuration(user.createTime),
  }));
  console.log(userDurations);
  const chart = echarts.init(chartContainer.value);

  const option = {
    title: {
      text: '用户账号使用时长',
    },
    tooltip: {},
    xAxis: {
      type: 'category',
      data: userDurations.map(user => user.name),
    },
    yAxis: {
      type: 'value',
      name: '使用时长 (天)',
    },
    series: [
      {
        data: userDurations.map(user => user.duration),
        type: 'bar',
      },
    ],
  };

  chart.setOption(option);

  window.addEventListener('resize', () => {
    chart.resize();
  });
});
</script>
